<template>
  <up-modal 
    :show="visible" 
    title=""
    :show-cancel-button="false"
    :show-confirm-button="false"
    :closeOnClickOverlay="true"
  >
    <view class="login-container">
      <!-- 登录图标 -->
      <view class="login-icon">
        <up-icon customPrefix="iconfont" name="login1" size="56" color="#00c35e"></up-icon>
      </view>
      
      <!-- 登录标题 -->
      <view class="login-title">
        <text class="title-text">欢迎使用任务平台</text>
        <text class="subtitle-text">登录后体验完整功能</text>
      </view>
      
      <!-- 登录方式选择 -->
      <view class="login-methods">
        <!-- 微信登录（H5环境） -->
        <view 
          class="login-btn wechat-btn" 
          @click="handleWechatLogin"
          :class="{'btn-loading': loading}"
        >
          <up-icon name="weixin-circle-fill" size="24" color="#ffffff" />
          <text class="btn-text">微信一键登录</text>
          <up-loading-icon v-if="loading" mode="semicircle" text="" size="18" color="#ffffff"></up-loading-icon>
        </view>

      </view>
      
      <!-- 用户协议 -->
      <view class="agreement">
        <text>登录即表示同意</text>
        <text class="agreement-link" @click="showUserAgreement">《用户协议》</text>
        <text>和</text>
        <text class="agreement-link" @click="showPrivacyPolicy">《隐私政策》</text>
      </view>
    </view>
    <template #popupBottom>
      <view class="close-button" style="margin-top: 20px;" @click="handleClose">
        <up-icon customPrefix="iconfont" name="close" color="#fff" size="24" :bold="true"></up-icon>
      </view>
    </template>
  </up-modal>
  
  <!-- 协议弹窗 -->
  <u-modal 
    v-model="showAgreementModal" 
    :title="agreementTitle"
    :show-confirm-button="false"
    :show-cancel-button="false"
    close-on-click-overlay
  >
    <view class="agreement-content">
      <scroll-view scroll-y style="max-height: 400px;">
        <rich-text :nodes="agreementContent"></rich-text>
      </scroll-view>
      <u-button type="primary" size="default" @click="closeAgreementModal">我知道了</u-button>
    </view>
  </u-modal>
</template>

<script>
import { defineComponent, ref, computed, onUnmounted, watch } from 'vue';
import { useUserStore } from '../store/user.js';
import { isWechat, getWechatUserProfile } from '../utils/wx.js';
import { validatePhone } from '../utils/common.js';
import { wxLogin } from '../api/auth.js';

export default defineComponent({
  name: 'LoginModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  emits: ['close', 'success', 'error', 'update:visible', 'loginSuccess'],
  setup(props, { emit }) {
    // 监听visible变化，当弹窗关闭时重置表单
    watch(() => props.visible, (newVal, oldVal) => {
      if (oldVal && !newVal) {
        resetForm();
        emit('close');
      }
    });
    
    const userStore = useUserStore();
    const loading = ref(false);
    const phone = ref('');
    const code = ref('');
    const countdown = ref(0);
    const timer = ref(null);
    
    // 协议相关
    const showAgreementModal = ref(false);
    const agreementTitle = ref('');
    const agreementContent = ref('');
    
    // 计算属性
    const isWechatEnv = computed(() => isWechat());
    const canSendCode = computed(() => validatePhone(phone.value) && countdown.value === 0);
    const codeButtonText = computed(() => countdown.value > 0 ? `${countdown.value}秒后重新获取` : '获取验证码');
    
    // 通用登录成功处理
    const handleLoginSuccess = (userInfo, token) => {
      userStore.setUserInfo(userInfo);
      userStore.setToken(token);
      userStore.setLoggedIn(true);
      
      uni.showToast({ title: '登录成功', icon: 'success' });
      emit('update:modelValue', false);
      resetForm();
      emit('close');
      emit('success', { userInfo, token });
      emit('loginSuccess', { userInfo, token });
    };
    
    // 微信登录
    const handleWechatLogin = async () => {
      console.log('handleWechatLogin');
      try {
        loading.value = true;
        
        const authResult = await getWechatUserProfile();
        
        if (authResult?.code) {
          const loginResult = await wxLogin(authResult.code);
          
          if (loginResult.code === 1) {
            handleLoginSuccess(loginResult.data.userInfo || {}, loginResult.data.token || '');
          } else {
            uni.showToast({ title: loginResult.msg || '登录失败', icon: 'none' });
            emit('error', loginResult);
          }
        }
      } catch (error) {
        console.error('微信登录失败:', error);
        uni.showToast({ title: '微信登录失败，请稍后重试', icon: 'none' });
        emit('error', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 手机号登录
    const handlePhoneLogin = async () => {
      if (!validatePhone(phone.value)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
        return;
      }
      
      if (!code.value || code.value.length !== 6) {
        uni.showToast({ title: '请输入6位验证码', icon: 'none' });
        return;
      }
      
      try {
        loading.value = true;
        // const result = await phoneLogin(phone.value, code.value); // 实际接口调用
        
        // 模拟登录成功
        const mockUserInfo = {
          id: '1',
          nickname: '测试用户',
          avatar: '',
          phone: phone.value
        };
        const mockToken = 'mock_token_' + Date.now();
        
        handleLoginSuccess(mockUserInfo, mockToken);
      } catch (error) {
        console.error('手机号登录失败:', error);
        uni.showToast({ title: '登录失败，请稍后重试', icon: 'none' });
        emit('error', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 协议相关
    const showUserAgreement = () => {
      agreementTitle.value = '用户协议';
      agreementContent.value = '<div>用户协议内容...</div>';
      showAgreementModal.value = true;
    };
    
    const showPrivacyPolicy = () => {
      agreementTitle.value = '隐私政策';
      agreementContent.value = '<div>隐私政策内容...</div>';
      showAgreementModal.value = true;
    };
    
    const closeAgreementModal = () => {
      showAgreementModal.value = false;
    };
    
    // 重置表单
    const resetForm = () => {
      phone.value = '';
      code.value = '';
      if (timer.value) {
        clearInterval(timer.value);
        countdown.value = 0;
      }
    };
    
    // 关闭弹窗
    const handleClose = () => {
      emit('update:visible', false);
      emit('close');
      resetForm();
    };
    
    // 组件卸载时清理定时器
    onUnmounted(() => {
      if (timer.value) clearInterval(timer.value);
    });
    
    return {
      loading,
      phone,
      code,
      countdown,
      canSendCode,
      codeButtonText,
      isWechatEnv,
      showAgreementModal,
      agreementTitle,
      agreementContent,
      handleWechatLogin,
      handlePhoneLogin,
      showUserAgreement,
      showPrivacyPolicy,
      closeAgreementModal,
      handleClose
    };
  }
});
</script>

<style lang="scss" scoped>
.login-container {
  padding: 20px 0;
}

.login-icon {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  
  .title-text {
    display: block;
    font-size: 20px;
    font-weight: 600;
    color: #333333;
    margin-bottom: 8px;
  }
  
  .subtitle-text {
    display: block;
    font-size: 14px;
    color: #666666;
  }
}

.login-methods {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
  height: 44px;
  border-radius: 22px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  transition: all 0.3s ease;
  
  &:active {
    opacity: 0.8;
  }
  
  .btn-text {
    color: #ffffff;
  }
}

.wechat-btn {
  background-color: #00c35e;
  
  &.btn-loading {
    opacity: 0.8;
  }
}

.agreement {
  text-align: center;
  font-size: 12px;
  color: #999999;
  line-height: 1.5;
  
  .agreement-link {
    color: #409eff;
    margin: 0 4px;
  }
}

.agreement-content {
  .u-button {
    margin-top: 20px;
  }
}

// 深色模式适配
:global(.dark-theme) .login-title {
  .title-text {
    color: #ffffff;
  }
  
  .subtitle-text {
    color: #cccccc;
  }
}

:global(.dark-theme) .agreement {
  color: #666666;
}
</style>